package main

import (
	"fmt"
	"io/ioutil"
	"strconv"

	"gopkg.in/yaml.v2"
)

// yaml读写

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

type Study struct {
	CourseName string `yaml:"CourseName"`
	Score      int    `yaml:"Score"`
}

type Student struct {
	Name      string  `yaml:"name"`
	Address   string  `yaml:"addr"`
	ScoreList []Study `yaml:"ScoreList"`
}

// 写
func writeToYmal(filepath string) {
	var stu = &Student{
		Name:      "xsq",
		Address:   "上海",
		ScoreList: []Study{{"语文", 100}, {"数学", 100}, {"英语", 100}, {"地理", 0}},
	}
	data, err := yaml.Marshal(stu)
	checkError(err)
	err = ioutil.WriteFile(filepath, data, 0777)
	checkError(err)
}

// 读
func readFormYaml(filepath string) {
	content, err := ioutil.ReadFile(filepath)
	checkError(err)
	newStu := &Student{}
	err = yaml.Unmarshal(content, &newStu)
	checkError(err)
	ScoreList := newStu.ScoreList
	fmt.Println(newStu.Name + "的学习情况")
	for _, v := range ScoreList {
		fmt.Println("Course:" + v.CourseName + "\tScore:" + strconv.Itoa(v.Score))
	}
}

func main() {
	filepath := "./c.yaml"
	writeToYmal(filepath)
	readFormYaml(filepath)
}
